package com.shixu.framework.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanUtils extends org.apache.commons.beanutils.BeanUtils {
	
	public static void mergeProperties(Object dest, Object orig) {
	    
		Class<?> c = orig.getClass();
		Field[] fileds = c.getDeclaredFields();
		
		for (Field field : fileds) {
			field.setAccessible(true);
			try {
				Object value = field.get(orig);
				mergeProperty(dest, field.getName(), value);
			} catch (Exception e) {
			}
			
		}
		
    }
	
	public static void mergeProperty(Object bean, String name, Object value) {

		if (value != null) {
			try {
				copyProperty(bean, name, value);
			} catch (IllegalAccessException e) {
			} catch (InvocationTargetException e) {
			}
		}
    }
	
	/**
	 * 取得JavaBean中的所有字段名称
	 * @param bean
	 * @return
	 */
	public static String[] getFieldNm(Object bean){
		if (bean == null) {
			return null;
		}
		Field[] fields = bean.getClass().getDeclaredFields();
		
		String[] fieldNms = new String[fields.length];
		for (int i = 0; i < fieldNms.length; i++) {
			fields[i].setAccessible(true);
			fieldNms[i] = fields[i].getName();
		}
		
		return fieldNms;
	}
	
	/**
	 * 转换JavaBean为Map<String,Object>类型
	 * @param obj
	 * @return
	 */
	public static Map<String, Object> transBean2Map(Object obj) {  
		  
        if(obj == null){  
            return null;  
        }          
        Map<String, Object> map = new HashMap<String, Object>();  
        try {  
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());  
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
            for (PropertyDescriptor property : propertyDescriptors) {  
                String key = property.getName();  
  
                // 过滤class属性  
                if (!key.equals("class")) {  
                    // 得到property对应的getter方法  
                    Method getter = property.getReadMethod();  
                    Object value = getter.invoke(obj);  
  
                    map.put(key, value);  
                }  
  
            }  
        } catch (Exception e) {  
            System.out.println("transBean2Map Error " + e);  
        }  
  
        return map;  
  
    }  
		
}
